package com.leyou.item.web;

import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.service.CategoryService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("category")
public class CategoryController {

    private final CategoryService categoryService;

    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    /**
     * 根据分类id，查询商品分类
     * @param id 分类的id
     * @return 返回商品分类对象
     */
    @GetMapping("/{id}")
    public ResponseEntity<CategoryDTO> queryById(@PathVariable("id") Long id){
        // 查询数据库，得到po
        //Category category = categoryService.getById(id);
        // 转为dto
        //CategoryDTO dto = new CategoryDTO(categoryService.getById(id));
        // 返回200,带上结果
        return ResponseEntity.ok(new CategoryDTO(categoryService.getById(id)));
    }

    /**
     * 根据分类id的集合，查询商品分类的集合
     * @param ids id集合
     * @return 分类集合
     */
    @GetMapping("list")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByIds(@RequestParam("ids") List<Long> ids){
        // 查询数据库，得到po
        List<Category> list = categoryService.listByIds(ids);
        // 转为dto
        List<CategoryDTO> dtoList = CategoryDTO.convertEntityList(list);
        // 返回200,带上结果
        return ResponseEntity.ok(dtoList);
    }

    /**
     * 根据分类id的集合，查询商品分类的集合
     * @param pid 父类目id
     * @return 分类集合
     */
    @GetMapping("/of/parent")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByParent(@RequestParam("pid") Long pid){
        return ResponseEntity.ok(
                CategoryDTO.convertEntityList(
                        categoryService.query().eq("parent_id", pid).list()
                )
        );
    }
}
